package com.itheima.aimobile.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.aimobile.domain.ChatHistory;
import com.itheima.aimobile.mapper.ChatHistoryMapper;
import com.itheima.aimobile.mapper.ConversationMapper;
import com.itheima.aimobile.service.IChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatHistoryImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {
    private final ConversationMapper conversationMapper;

    /**
     * 保存聊天历史
     * 幂等：在这个方法执行一次或者多次，结果是一样的
     * @param type
     * @param chatId
     */
    @Override
    public void saveChatHistory(String type,String chatId) {
        //先查询有没有，如果没有再新增
        //sql：select count(*) from chat_history where chatId = ? and type = ?
        //lambdaQuery：list count page one
        Long count = lambdaQuery()
                .eq(ChatHistory::getConversationId, chatId)
                .eq(ChatHistory::getType, type)
                .count();
        if(count!=null&&count>0){
            //有记录
            return;
        }
        //代码走到这里说明没有历史，save
        ChatHistory chatHistory = ChatHistory.builder()
                .conversationId(chatId)
                .userId(null)
                .title(type + chatId)
                .createTime(LocalDateTime.now())
                .type(type)
                .build();
        this.save(chatHistory);
    }

    @Override
    public List<String> getChatIds(String type, Long userId) {
        //sql：select * from chat_history where type = ? and userId = ?
        List<ChatHistory> list = lambdaQuery()
                .eq(ChatHistory::getType, type)
                .eq(userId != null, ChatHistory::getUserId, userId)
                .list();
        return list.stream().map(ChatHistory::getConversationId).toList();
    }
}